package my.music.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import my.music.common.result.Result;
import my.music.common.result.ResultEnum;
import my.music.common.result.ResultModel;
import my.music.dao.UserAdminMapper;
import my.music.pojo.UserAdmin;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.websocket.server.PathParam;
import java.math.BigInteger;

/**
 * 管理员
 */
@RestController
@RequestMapping("admin/api")
@SaCheckRole("admin")
public class AdminController {
    @Resource
    private UserAdminMapper userAdminMapper;

    /**
     * 添加管理员
     * @param userAdmin
     * @RequestHeader("token") String token
     * @return
     */
    @PostMapping("add")
    public Result<UserAdmin> addAdmin(@Validated UserAdmin userAdmin){
        // 判断是否存在
        QueryWrapper qw = new QueryWrapper<>()
                .eq("user_id", userAdmin.getUserId());
        UserAdmin res = userAdminMapper.selectOne(qw);
        if (res != null){
            return ResultModel.error(ResultEnum.USER_EXIST);
        }

        int insert = userAdminMapper.insert(userAdmin);
        if (insert > 0){
            return ResultModel.success(userAdmin);
        }
        return ResultModel.error(ResultEnum.SYSTEM_RUN_ERROR);
    }

    /**
     * 删除管理员权限
     * @param id 管理员id
     * @RequestHeader
     * @return
     */
    @GetMapping("delete/{id}")
    public Result deleteAdmin(@PathVariable("id") BigInteger id){
        int i = userAdminMapper.deleteById(id);
        if (i > 0){
            return ResultModel.success();
        }
        return ResultModel.error(ResultEnum.SYSTEM_RUN_ERROR);
    }

    /**
     * 分页获取管理员信息
     * @param current 页码
     * @param size 长度（默认10）
     * @return
     */
    @GetMapping("list/admin/{current}")
    public Result<Page<UserAdmin>> listAdminUserInfo(@PathVariable("current") Long current, @PathParam("size") Long size){
        Page page = new Page();
        page.setCurrent(current);
        if (size != null) page.setSize(size);
        IPage listIPage = userAdminMapper.listAdminUserInfoPage(page);
        return ResultModel.success(listIPage);
    }
}
